package game;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;

/**
 * Play MIDI files
 * @author Simon
 *
 */
public class MidiPlayer {
	javax.microedition.media.Player p;
	boolean playing = false;
	
	public MidiPlayer() {
		
	}
	
	public void play(String path) {
		InputStream is = getClass().getResourceAsStream(path);
		if (is == null) {
			System.err.println("couldn't load midi file " + path);
			return;
		}
		try {
			p = Manager.createPlayer(is, "audio/midi");
			p.setLoopCount(-1);
			p.realize();
			p.prefetch();
			p.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		playing = true;
	}
	
	public void pause() {
		try {
			p.stop();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		playing = false;
	}
	
	public void resume() {
		try {
			p.start();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		playing = true;
	}
	
	public void togglePause() {
		if (!playing) {
			resume();
		} else {
			pause();
		}
	}
}
